package repository

import (
	"context"
	"gitee.com/jinmingzhi/cdce-service/internal/model"
	"gitee.com/jinmingzhi/kit/rdb"
)

const (
	schoolReportAddField           = "uid, batch_time_id, course_id, area_school_id, school_time, status, result, create_time"
	schoolReportField              = "id, uid, batch_time_id, course_id, area_school_id, school_time, status, result, create_time"
	schoolReportAddOneSql          = "insert into`" + SCHOOLREPORT + "`(" + schoolReportAddField + ") values(?,?,?,?,?,?,?,?)"
	schoolReportFindAllByUIDsql    = "select " + schoolReportField + " from `" + SCHOOLREPORT + "` where uid=?"
	schoolReportModifyResultOneSql = "update `" + SCHOOLREPORT + "` set result=?,status=? where uid=? "

	findScoreAllByUidFiled = "`" + SCHOOLREPORT + "`.id,`" + BATCHTIME + "`.batch_name,`" + COURSE + "`.course_name,`" + SCHOOLREPORT + "`.status,`" + SCHOOLREPORT + "`.result"
	findScoreAllByUid      = "select " + findScoreAllByUidFiled + " from `" + SCHOOLREPORT + "` left join `" + BATCHTIME + "` on `" + SCHOOLREPORT + "`.batch_time_id=`" + BATCHTIME + "`.id left join `" + COURSE + "` on `" + SCHOOLREPORT + "`.course_id=`" + COURSE + "`.id where `" + SCHOOLREPORT + "`.uid=? and  `" + SCHOOLREPORT + "`.status=?"
)

type SchoolReport interface {
	AddOne(ctx context.Context, data *model.SchoolReport) error
	ModifyResultOne(ctx context.Context, uid uint32, result float32) error
	FindAllByUid(ctx context.Context, uid uint32) ([]*model.SchoolReport, error)
	FindScoreAllByUid(ctx context.Context, uid uint32) ([]*model.Score, error)
}

type SchoolReportImpl struct {
	repo rdb.Repository
}

func NewSchoolReport(repo rdb.Repository) SchoolReport {
	return &SchoolReportImpl{repo: repo}
}

func (s *SchoolReportImpl) AddOne(ctx context.Context, data *model.SchoolReport) error {
	_, err := s.repo.AddOne(ctx, schoolReportAddOneSql, data.UID, data.BatchTimeID, data.CourseID, data.AreaSchoolID, data.SchoolTime, data.Status, data.Result, data.CreateTime)
	if err != nil {
		return err
	}
	return nil
}

func (s *SchoolReportImpl) ModifyResultOne(ctx context.Context, uid uint32, result float32) error {
	return s.repo.SaveOne(ctx, schoolReportModifyResultOneSql, result, 1, uid)

}

func (s *SchoolReportImpl) FindAllByUid(ctx context.Context, uid uint32) ([]*model.SchoolReport, error) {
	data := []*model.SchoolReport{}
	err := s.repo.FindAll(ctx, &data, schoolReportFindAllByUIDsql, uid)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (s *SchoolReportImpl) FindScoreAllByUid(ctx context.Context, uid uint32) ([]*model.Score, error) {
	data := []*model.Score{}
	err := s.repo.FindAll(ctx, &data, findScoreAllByUid, uid, true)
	if err != nil {
		return nil, err
	}
	return data, nil
}
